
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>血糖记录管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-lg">
        <div class="max-w-7xl mx-auto px-4">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-2">
                    <i class="fas fa-heartbeat text-red-500 text-2xl"></i>
                    <h1 class="text-2xl font-bold text-gray-800">血糖记录系统</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="settingsBtn" class="p-2 rounded-full hover:bg-gray-100">
                        <i class="fas fa-cog text-gray-600"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="max-w-7xl mx-auto px-4 py-8">
        <!-- 控制面板 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-8">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h2 class="text-xl font-semibold text-gray-800">血糖记录管理</h2>
                    <p class="text-gray-600 mt-1">记录并追踪您的血糖测量结果</p>
                </div>
                <div class="flex flex-wrap gap-3">
                    <button id="addRecordBtn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
                        <i class="fas fa-plus"></i>
                        添加记录
                    </button>
                    <button id="downloadBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
                        <i class="fas fa-download"></i>
                        下载表格
                    </button>
                    <button id="clearAllBtn" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
                        <i class="fas fa-trash"></i>
                        清空数据
                    </button>
                </div>
            </div>
        </div>

        <!-- 数据表格区域 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">血糖值 (mg/dL)</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">测量时段</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">备注</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody id="recordsTable" class="bg-white divide-y divide-gray-200">
                        <!-- 记录将通过JavaScript动态添加 -->
                    </tbody>
                </table>
            </div>
            <div id="emptyState" class="text-center py-12">
                <i class="fas fa-clipboard-list text-gray-300 text-5xl mb-4"></i>
                <h3 class="text-lg font-medium text-gray-500">暂无血糖记录</h3>
                <p class="text-gray-400 mt-1">点击"添加记录"按钮开始记录您的血糖测量结果</p>
            </div>
        </div>

        <!-- 统计信息区域 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-8">
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500">平均血糖值</p>
                        <p id="avgGlucose" class="text-2xl font-bold text-gray-800 mt-1">--</p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <i class="fas fa-chart-line text-blue-500 text-xl"></i>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500">记录总数</p>
                        <p id="totalRecords" class="text-2xl font-bold text-gray-800 mt-1">0</p>
                    </div>
                    <div class="bg-green-100 p-3 rounded-full">
                        <i class="fas fa-list text-green-500 text-xl"></i>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500">最近记录</p>
                        <p id="latestRecord" class="text-2xl font-bold text-gray-800 mt-1">--</p>
                    </div>
                    <div class="bg-purple-100 p-3 rounded-full">
                        <i class="fas fa-clock text-purple-500 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 添加/编辑记录模态框 -->
    <div id="recordModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-xl shadow-2xl max-w-md w-full p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-gray-800" id="modalTitle">添加血糖记录</h3>
                <button id="closeModal" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <form id="recordForm" class="space-y-4">
                <input type="hidden" id="editIndex">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">测量日期</label>
                    <input type="date" id="recordDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">测量时间</label>
                    <input type="time" id="recordTime" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">血糖值 (mg/dL)</label>
                    <input type="number" id="glucoseValue" min="0" max="500" step="0.1" value="6" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="例如: 120.5" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">测量时段</label>
                    <select id="measurementPeriod" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        <option value="">请选择时段</option>
                        <option value="空腹">空腹</option>
                        <option value="早餐后">早餐后</option>
                        <option value="午餐前">午餐前</option>
                        <option value="午餐后">午餐后</option>
                        <option value="晚餐前">晚餐前</option>
                        <option value="晚餐后">晚餐后</option>
                        <option value="睡前">睡前</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
                    <textarea id="recordNote" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="可选的备注信息..."></textarea>
                </div>
                <div class="flex justify-end gap-3 pt-4">
                    <button type="button" id="cancelBtn" class="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors">取消</button>
                    <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors">保存记录</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 mt-12">
        <div class="max-w-7xl mx-auto px-4 py-6">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="flex items-center space-x-2">
                    <i class="fas fa-heartbeat text-red-500"></i>
                    <span class="text-gray-600">血糖记录管理系统 &copy; 2025</span>
                </div>
                <div class="mt-4 md:mt-0">
                    <p class="text-gray-500 text-sm">健康管理，从记录开始</p>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // 血糖记录数据管理
        class GlucoseRecordManager {
            constructor() {
                this.records = this.loadRecords();
                this.initializeEventListeners();
                this.renderTable();
                this.updateStatistics();
            }

            // 从localStorage加载记录
            loadRecords() {
                const stored = localStorage.getItem('glucoseRecords');
                return stored ? JSON.parse(stored) : [];
            }

            // 保存记录到localStorage
            saveRecords() {
                localStorage.setItem('glucoseRecords', JSON.stringify(this.records));
            }

            // 添加新记录
            addRecord(record) {
                this.records.push(record);
                this.saveRecords();
                this.renderTable();
                this.updateStatistics();
            }

            // 编辑记录
            editRecord(index, updatedRecord) {
                this.records[index] = updatedRecord;
                this.saveRecords();
                this.renderTable();
                this.updateStatistics();
            }

            // 删除记录
            deleteRecord(index) {
                if (confirm('确定要删除这条记录吗？')) {
                    this.records.splice(index, 1);
                    this.saveRecords();
                    this.renderTable();
                    this.updateStatistics();
                }
            }

            // 清空所有记录
            clearAllRecords() {
                if (this.records.length === 0) {
                    alert('当前没有记录可清空');
                    return;
                }

                if (confirm('确定要清空所有血糖记录吗？此操作不可撤销！')) {
                    this.records = [];
                    this.saveRecords();
                    this.renderTable();
                    this.updateStatistics();
                }
            }

            // 渲染表格
            renderTable() {
                const tableBody = document.getElementById('recordsTable');
                const emptyState = document.getElementById('emptyState');

                if (this.records.length === 0) {
                    tableBody.innerHTML = '';
                    emptyState.classList.remove('hidden');
                    return;
                }

                emptyState.classList.add('hidden');
                tableBody.innerHTML = this.records.map((record, index) => `
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.date}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.time}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs font-semibold rounded-full ${
                                record.glucoseValue < 70 ? 'bg-red-100 text-red-800' : 
                                record.glucoseValue > 180 ? 'bg-yellow-100 text-yellow-800' : 
                                'bg-green-100 text-green-800'
                            }">
                                ${record.glucoseValue} mg/dL
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.period}</td>
                        <td class="px-6 py-4 text-sm text-gray-900">${record.note || '-'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button class="text-blue-600 hover:text-blue-900 mr-3 edit-record" data-index="${index}">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="text-red-600 hover:text-red-900 delete-record" data-index="${index}">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `).join('');
            }

            // 更新统计信息
            updateStatistics() {
                const totalRecords = document.getElementById('totalRecords');
                const avgGlucose = document.getElementById('avgGlucose');
                const latestRecord = document.getElementById('latestRecord');

                totalRecords.textContent = this.records.length;

                if (this.records.length > 0) {
                    const avg = this.records.reduce((sum, record) => sum + parseFloat(record.glucoseValue), 0) / this.records.length;
                    avgGlucose.textContent = avg.toFixed(1) + ' mg/dL';

                    const latest = this.records[this.records.length - 1];
                    latestRecord.textContent = latest.glucoseValue + ' mg/dL';
                } else {
                    avgGlucose.textContent = '--';
                    latestRecord.textContent = '--';
                }
            }

            // 下载表格数据
            downloadTable() {
                if (this.records.length === 0) {
                    alert('没有记录可下载');
                    return;
                }

                let csvContent = "data:text/csv;charset=utf-8,\uFEFF";
                csvContent += "日期,时间,血糖值(mg/dL),测量时段,备注\n";

                this.records.forEach(record => {
                    const row = [
                        record.date,
                        record.time,
                        record.glucoseValue,
                        record.period,
                        record.note || ''
                    ];
                    csvContent += row.map(field => `"${field}"`).join(",") + "\n";
                });

                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "血糖记录.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }

            // 初始化事件监听器
            initializeEventListeners() {
                const addRecordBtn = document.getElementById('addRecordBtn');
                const downloadBtn = document.getElementById('downloadBtn');
                const clearAllBtn = document.getElementById('clearAllBtn');
                const recordModal = document.getElementById('recordModal');
                const closeModal = document.getElementById('closeModal');
                const cancelBtn = document.getElementById('cancelBtn');
                const recordForm = document.getElementById('recordForm');

                // 打开添加记录模态框
                addRecordBtn.addEventListener('click', () => {
                    document.getElementById('modalTitle').textContent = '添加血糖记录';
                    document.getElementById('editIndex').value = '';
                    recordForm.reset();
                    recordModal.classList.remove('hidden');
					//默认当前时间
					//const now = new Date();
					//const formattedTime = now.toISOString().slice(0,  16); // 格式化为YYYY-MM-DDThh:mm
					//document.getElementById('recordTime').value  = formattedTime;
					
					// 获取当前时间
					const formattedDate = new Date().toISOString().split('T')[0];
					// 设置input默认值
					document.getElementById('recordDate').value  = formattedDate;

					const now = new Date();
					// 格式化时分（24小时制）
					const hours = String(now.getHours()).padStart(2,  '0'); // 小时补零
					const minutes = String(now.getMinutes()).padStart(2,  '0'); // 分钟补零
					// 拼接为标准格式（可选添加秒：`${hours}:${minutes}:${seconds}`）
					const formattedTime = `${hours}:${minutes}`;
					// 设置input默认值
					document.getElementById('recordTime').value  = formattedTime;
                });

                // 下载表格
                downloadBtn.addEventListener('click', () => {
                    this.downloadTable();
                });

                // 清空所有记录
                clearAllBtn.addEventListener('click', () => {
                    this.clearAllRecords();
                });

                // 关闭模态框
                closeModal.addEventListener('click', () => {
                    recordModal.classList.add('hidden');
                });

                cancelBtn.addEventListener('click', () => {
                    recordModal.classList.add('hidden');
                });

                // 表单提交
                recordForm.addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.handleFormSubmit();
                });

                // 委托事件处理编辑和删除按钮
                document.addEventListener('click', (e) => {
                    if (e.target.closest('.edit-record')) {
                        const index = e.target.closest('.edit-record').getAttribute('data-index');
                        this.openEditModal(parseInt(index));
                    }

                    if (e.target.closest('.delete-record')) {
                        const index = e.target.closest('.delete-record').getAttribute('data-index');
                        this.deleteRecord(parseInt(index));
                    }
                });

                // 设置默认日期为今天
                const today = new Date().toISOString().split('T')[0];
                document.getElementById('recordDate').value = today;
            }

            // 处理表单提交
            handleFormSubmit() {
                const editIndex = document.getElementById('editIndex').value;
                const record = {
                    date: document.getElementById('recordDate').value,
                    time: document.getElementById('recordTime').value,
                    glucoseValue: parseFloat(document.getElementById('glucoseValue').value),
                    period: document.getElementById('measurementPeriod').value,
                    note: document.getElementById('recordNote').value
                };

                if (editIndex === '') {
                    this.addRecord(record);
                } else {
                    this.editRecord(parseInt(editIndex), record);
                }

                document.getElementById('recordModal').classList.add('hidden');
            }

            // 打开编辑模态框
            openEditModal(index) {
                const record = this.records[index];
                document.getElementById('modalTitle').textContent = '编辑血糖记录';
                document.getElementById('editIndex').value = index;
                document.getElementById('recordDate').value = record.date;
                document.getElementById('recordTime').value = record.time;
                document.getElementById('glucoseValue').value = record.glucoseValue;
                document.getElementById('measurementPeriod').value = record.period;
                document.getElementById('recordNote').value = record.note || '';

                document.getElementById('recordModal').classList.remove('hidden');
            }
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            new GlucoseRecordManager();
        });
    </script>
</body>
</html>
<code_end>

该血糖记录系统具有以下功能和特点：
1. 完整的血糖记录管理功能，支持添加、编辑、删除和查看操作
2. 数据持久化存储，使用localStorage保存用户记录
3. 响应式表格设计，适配不同屏幕尺寸
4. 一键下载功能，可将表格数据导出为CSV文件
5. 实时统计信息显示，包括平均血糖值、记录总数和最近记录
6. 现代化UI设计，采用渐变背景、阴影效果和圆角元素
7. 血糖值颜色编码，根据数值范围显示不同颜色标识
8. 表单验证和用户友好的交互提示
9. 完整的空状态处理，提升用户体验
10. 使用Tailwind CSS和Font Awesome图标库，确保界面美观一致